package com.huawei.translate.notification.builders;

import com.huawei.translate.model.Application;
import com.huawei.translate.notification.EmailEntity;
import com.huawei.translate.notification.model.EmailTemplate;
import com.huawei.translate.notification.repository.EmailTemplateRepository;
import com.huawei.translate.notification.service.EmailTemplateType;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ApplicationSubmissionEmailBuilder implements EmailBuilder {

    private Logger logger = Logger.getLogger(ApplicationSubmissionEmailBuilder.class);

    private static EmailTemplateType templateName = EmailTemplateType.ApplicationSubmission;

    @Value("${website}")
    private String website;

    @Autowired
    private EmailTemplateRepository emailTemplateRepository;

    private Application application;

    @Value("${admin.emails}")
    private String emails;

    @Value("${sys.email}")
    private String sysEmail;

    public EmailTemplateType getTemplateName() {
        return templateName;
    }

    public ApplicationSubmissionEmailBuilder WithApplication(Application application) {
        this.application = application;
        return this;
    }

    public EmailEntity build() {
        EmailEntity emailEntity = new EmailEntity();
        emailEntity.setSubject("翻译服务申请通知");
        emailEntity.setFrom(sysEmail);
        emailEntity.setTo(emails);
        logger.info("Template Name is:" + templateName.name());
        List<EmailTemplate> templateList = emailTemplateRepository.findAll();
        for (EmailTemplate emailTemplate : templateList) {
            logger.info("There is template:" + emailTemplate.getTemplateName());
        }
        List<EmailTemplate> templates = emailTemplateRepository.findByTemplateName(templateName.name());
        if (templates.size() < 1 || templates == null) {
            logger.info("Can not find ApplicationSubmission email template");
            emailEntity.setContent("");
            return emailEntity;
        }
        EmailTemplate template = templates.get(0);
        String content = template.getTemplate();
        String result = String.format(content,
                application.getAppName(),
                application.getOnlineDate().toString(),
                application.getAccessCountPerSec().toString(),
                application.getLanguages(),
                application.getDescription(),
                application.getStatus(),
                application.getInterfacePerson(),
                application.getProductOwner(),
                website
        );
        emailEntity.setContent(result);
        return emailEntity;
    }
}
